{% extends "rbac/base.html" %}
{% load static %}

{% block title %}菜单管理{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'rbac:welcome' %}">RBAC系统</a></li>
<li class="breadcrumb-item active" aria-current="page">菜单管理</li>
{% endblock %}

{% block extra_css %}
<style>
.alert-sm {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
}

.form-text {
    font-size: 0.8rem;
    line-height: 1.4;
}

.input-group .btn {
    border-left: 0;
}

.input-group .form-control:focus {
    border-color: #86b7fe;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

#urlTemplateSelect, #editUrlTemplateSelect {
    font-size: 0.9rem;
}

#urlTemplateSelect option, #editUrlTemplateSelect option {
    padding: 0.5rem;
}

.url-validation-result {
    margin-top: 0.5rem;
}

/* 美化验证结果 */
.alert-success.alert-sm {
    background-color: #d1e7dd;
    border-color: #badbcc;
    color: #0f5132;
}

.alert-warning.alert-sm {
    background-color: #fff3cd;
    border-color: #ffecb5;
    color: #664d03;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .input-group {
        flex-direction: column;
    }
    
    .input-group .btn {
        border-left: 1px solid #ced4da;
        border-top: 0;
        border-radius: 0 0 0.375rem 0.375rem;
    }
    
    .input-group .form-control {
        border-radius: 0.375rem 0.375rem 0 0;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">
            <i class="fas fa-bars text-primary me-2"></i>菜单管理
        </h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMenuModal">
            <i class="fas fa-plus me-1"></i>添加菜单
        </button>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-primary text-white">
                <div class="card-body text-center">
                    <i class="fas fa-bars fa-2x mb-2"></i>
                    <h4 class="mb-1">{{ menus|length }}</h4>
                    <small>总菜单数</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-success text-white">
                <div class="card-body text-center">
                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                    <h4 class="mb-1">{{ menus|length }}</h4>
                    <small>启用菜单</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-warning text-white">
                <div class="card-body text-center">
                    <i class="fas fa-users fa-2x mb-2"></i>
                    <h4 class="mb-1">{{ roles|length }}</h4>
                    <small>关联角色</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-info text-white">
                <div class="card-body text-center">
                    <i class="fas fa-shield-alt fa-2x mb-2"></i>
                    <h4 class="mb-1">{{ current_user.roles|length }}</h4>
                    <small>我的角色</small>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索和过滤 -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" class="form-control" id="searchMenu" placeholder="搜索菜单名称或代码...">
                    </div>
                </div>
                <div class="col-md-3">
                    <select class="form-select" id="statusFilter">
                        <option value="">所有状态</option>
                        <option value="active">启用</option>
                        <option value="inactive">禁用</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <select class="form-select" id="colorFilter">
                        <option value="">所有颜色</option>
                        <option value="primary">Primary</option>
                        <option value="success">Success</option>
                        <option value="warning">Warning</option>
                        <option value="danger">Danger</option>
                        <option value="info">Info</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-outline-secondary w-100" onclick="clearFilters()">
                        <i class="fas fa-times me-1"></i>清空
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 菜单列表 -->
    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th width="40">
                                <input type="checkbox" class="form-check-input" id="selectAll">
                            </th>
                            <th>菜单信息</th>
                            <th>图标</th>
                            <th>链接</th>
                            <th>状态</th>
                            <th>角色权限</th>
                            <th>排序</th>
                            <th width="200">操作</th>
                        </tr>
                    </thead>
                    <tbody id="menuTableBody">
                        {% for menu in menus %}
                        <tr data-menu-id="{{ menu.id }}" class="menu-row">
                            <td>
                                <input type="checkbox" class="form-check-input menu-checkbox" value="{{ menu.id }}">
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="badge bg-{{ menu.color }} rounded-pill me-2" style="width: 8px; height: 8px;"></div>
                                    <div>
                                        <div class="fw-bold text-dark">{{ menu.name }}</div>
                                        <small class="text-muted">{{ menu.code }}</small>
                                        {% if menu.description %}
                                        <div><small class="text-muted">{{ menu.description }}</small></div>
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                            <td>
                                <i class="{{ menu.icon }} text-{{ menu.color }} fa-lg"></i>
                            </td>
                            <td>
                                <a href="{{ menu.url }}" target="_blank" class="text-decoration-none">
                                    {{ menu.url }}
                                    <i class="fas fa-external-link-alt ms-1 text-muted" style="font-size: 0.8em;"></i>
                                </a>
                            </td>
                            <td>
                                {% if menu.is_active %}
                                <span class="badge bg-success">启用</span>
                                {% else %}
                                <span class="badge bg-secondary">禁用</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="d-flex flex-wrap gap-1">
                                    {% for role in menu.required_roles.all %}
                                    <span class="badge bg-primary">{{ role.name }}</span>
                                    {% empty %}
                                    <span class="text-muted">所有用户</span>
                                    {% endfor %}
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-light text-dark">{{ menu.sort_order }}</span>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                            onclick="editMenu({{ menu.id }})" title="编辑">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    {% if menu.is_active %}
                                    <button type="button" class="btn btn-sm btn-outline-warning" 
                                            onclick="toggleMenuStatus({{ menu.id }})" title="禁用">
                                        <i class="fas fa-pause"></i>
                                    </button>
                                    {% else %}
                                    <button type="button" class="btn btn-sm btn-outline-success" 
                                            onclick="toggleMenuStatus({{ menu.id }})" title="启用">
                                        <i class="fas fa-play"></i>
                                    </button>
                                    {% endif %}
                                    <button type="button" class="btn btn-sm btn-outline-danger" 
                                            onclick="deleteMenu({{ menu.id }}, '{{ menu.name }}')" title="删除">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="8" class="text-center py-5">
                                <i class="fas fa-bars fa-3x text-muted mb-3"></i>
                                <p class="text-muted mb-0">暂无菜单数据</p>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加菜单模态框 -->
<div class="modal fade" id="addMenuModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-plus text-primary me-2"></i>添加菜单
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addMenuForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">菜单名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">菜单代码 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="code" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">菜单描述</label>
                        <textarea class="form-control" name="description" rows="2"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">菜单图标</label>
                                <input type="text" class="form-control" name="icon" value="fas fa-cube">
                                <div class="form-text">使用 Font Awesome 图标类名</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">菜单颜色</label>
                                <select class="form-select" name="color">
                                    <option value="primary">Primary</option>
                                    <option value="success">Success</option>
                                    <option value="warning">Warning</option>
                                    <option value="danger">Danger</option>
                                    <option value="info">Info</option>
                                    <option value="dark">Dark</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">排序</label>
                                <input type="number" class="form-control" name="sort_order" value="0">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">菜单链接 <span class="text-danger">*</span></label>
                        
                        <!-- URL模板选择 -->
                        <div class="mb-2">
                            <select class="form-select" id="urlTemplateSelect" onchange="applyUrlTemplate()">
                                <option value="">选择常用URL模板</option>
                                <option value="/rbac/">🔒 RBAC权限系统</option>
                                <option value="/rbac/dashboard/">📊 RBAC仪表板</option>
                                <option value="/rbac/welcome/">🏠 欢迎页面</option>
                                <option value="/rbac/user_management/">👥 用户管理</option>
                                <option value="/rbac/role_list/">🏷️ 角色管理</option>
                                <option value="/rbac/permission_list/">🔑 权限管理</option>
                                <option value="/rbac/menu_list/">🍽️ 菜单管理</option>
                                <option value="/pm/">📋 PM项目管理</option>
                                <option value="/pm/index/">📈 PM主页</option>
                                <option value="/admin/">⚙️ Django管理后台</option>
                                <option value="custom">✨ 自定义URL</option>
                            </select>
                        </div>
                        
                        <!-- URL输入框 -->
                        <div class="input-group">
                            <span class="input-group-text">🔗</span>
                            <input type="text" class="form-control" name="url" id="urlInput" required 
                                   placeholder="输入菜单链接，如：/rbac/ 或 /pm/index/">
                            <button class="btn btn-outline-secondary" type="button" onclick="validateUrl()">
                                <i class="fas fa-check"></i> 验证
                            </button>
                        </div>
                        
                        <!-- URL类型提示 -->
                        <div class="form-text">
                            <strong>支持的URL格式：</strong><br>
                            • Django内部URL：<code>/rbac/</code>、<code>/pm/index/</code><br>
                            • 外部链接：<code>https://example.com</code><br>
                            • 相对路径：<code>../dashboard/</code>
                        </div>
                        
                        <!-- URL验证结果 -->
                        <div id="urlValidationResult" class="mt-2"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">需要的角色</label>
                        <div class="row">
                            {% for role in roles %}
                            <div class="col-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="role_ids" value="{{ role.id }}" id="add_role_{{ role.id }}">
                                    <label class="form-check-label" for="add_role_{{ role.id }}">
                                        {{ role.name }}
                                    </label>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        <div class="form-text">不选择任何角色表示所有用户都可以访问</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitAddMenu()">
                    <i class="fas fa-save me-1"></i>保存
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑菜单模态框 -->
<div class="modal fade" id="editMenuModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-edit text-primary me-2"></i>编辑菜单
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editMenuForm">
                    <input type="hidden" name="menu_id" id="edit_menu_id">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">菜单名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="name" id="edit_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">菜单代码 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="code" id="edit_code" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">菜单描述</label>
                        <textarea class="form-control" name="description" id="edit_description" rows="2"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">菜单图标</label>
                                <input type="text" class="form-control" name="icon" id="edit_icon">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">菜单颜色</label>
                                <select class="form-select" name="color" id="edit_color">
                                    <option value="primary">Primary</option>
                                    <option value="success">Success</option>
                                    <option value="warning">Warning</option>
                                    <option value="danger">Danger</option>
                                    <option value="info">Info</option>
                                    <option value="dark">Dark</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">排序</label>
                                <input type="number" class="form-control" name="sort_order" id="edit_sort_order">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">菜单链接 <span class="text-danger">*</span></label>
                        
                        <!-- URL模板选择 -->
                        <div class="mb-2">
                            <select class="form-select" id="editUrlTemplateSelect" onchange="applyEditUrlTemplate()">
                                <option value="">选择常用URL模板</option>
                                <option value="/rbac/">🔒 RBAC权限系统</option>
                                <option value="/rbac/dashboard/">📊 RBAC仪表板</option>
                                <option value="/rbac/welcome/">🏠 欢迎页面</option>
                                <option value="/rbac/user_management/">👥 用户管理</option>
                                <option value="/rbac/role_list/">🏷️ 角色管理</option>
                                <option value="/rbac/permission_list/">🔑 权限管理</option>
                                <option value="/rbac/menu_list/">🍽️ 菜单管理</option>
                                <option value="/pm/">📋 PM项目管理</option>
                                <option value="/pm/index/">📈 PM主页</option>
                                <option value="/admin/">⚙️ Django管理后台</option>
                                <option value="custom">✨ 自定义URL</option>
                            </select>
                        </div>
                        
                        <!-- URL输入框 -->
                        <div class="input-group">
                            <span class="input-group-text">🔗</span>
                            <input type="text" class="form-control" name="url" id="edit_url" required 
                                   placeholder="输入菜单链接，如：/rbac/ 或 /pm/index/">
                            <button class="btn btn-outline-secondary" type="button" onclick="validateEditUrl()">
                                <i class="fas fa-check"></i> 验证
                            </button>
                        </div>
                        
                        <!-- URL验证结果 -->
                        <div id="editUrlValidationResult" class="mt-2"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">需要的角色</label>
                        <div class="row" id="edit_roles_container">
                            {% for role in roles %}
                            <div class="col-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="role_ids" value="{{ role.id }}" id="edit_role_{{ role.id }}">
                                    <label class="form-check-label" for="edit_role_{{ role.id }}">
                                        {{ role.name }}
                                    </label>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitEditMenu()">
                    <i class="fas fa-save me-1"></i>保存修改
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 搜索功能
document.getElementById('searchMenu').addEventListener('input', function() {
    filterMenus();
});

document.getElementById('statusFilter').addEventListener('change', function() {
    filterMenus();
});

document.getElementById('colorFilter').addEventListener('change', function() {
    filterMenus();
});

function filterMenus() {
    const searchText = document.getElementById('searchMenu').value.toLowerCase();
    const statusFilter = document.getElementById('statusFilter').value;
    const colorFilter = document.getElementById('colorFilter').value;
    const rows = document.querySelectorAll('.menu-row');
    
    rows.forEach(row => {
        const name = row.querySelector('.fw-bold').textContent.toLowerCase();
        const code = row.querySelector('.text-muted').textContent.toLowerCase();
        const statusBadge = row.querySelector('.badge');
        const colorDot = row.querySelector('.badge.rounded-pill');
        
        let showRow = true;
        
        // 搜索过滤
        if (searchText && !name.includes(searchText) && !code.includes(searchText)) {
            showRow = false;
        }
        
        // 状态过滤
        if (statusFilter) {
            const isActive = statusBadge.textContent.trim() === '启用';
            if ((statusFilter === 'active' && !isActive) || (statusFilter === 'inactive' && isActive)) {
                showRow = false;
            }
        }
        
        // 颜色过滤
        if (colorFilter && !colorDot.classList.contains('bg-' + colorFilter)) {
            showRow = false;
        }
        
        row.style.display = showRow ? '' : 'none';
    });
}

function clearFilters() {
    document.getElementById('searchMenu').value = '';
    document.getElementById('statusFilter').value = '';
    document.getElementById('colorFilter').value = '';
    filterMenus();
}

// URL模板处理功能
function applyUrlTemplate() {
    const select = document.getElementById('urlTemplateSelect');
    const input = document.getElementById('urlInput');
    const value = select.value;
    
    if (value && value !== 'custom') {
        input.value = value;
        validateUrl();
    } else if (value === 'custom') {
        input.value = '';
        input.focus();
    }
}

function applyEditUrlTemplate() {
    const select = document.getElementById('editUrlTemplateSelect');
    const input = document.getElementById('edit_url');
    const value = select.value;
    
    if (value && value !== 'custom') {
        input.value = value;
        validateEditUrl();
    } else if (value === 'custom') {
        input.value = '';
        input.focus();
    }
}

// URL验证功能
function validateUrl() {
    const input = document.getElementById('urlInput');
    const result = document.getElementById('urlValidationResult');
    const url = input.value.trim();
    
    if (!url) {
        result.innerHTML = '';
        return;
    }
    
    // URL格式验证
    const validation = validateUrlFormat(url);
    
    if (validation.valid) {
        result.innerHTML = `
            <div class="alert alert-success alert-sm mb-0">
                <i class="fas fa-check-circle"></i> 
                <strong>验证通过：</strong>${validation.type}
                ${validation.suggestion ? '<br><small>' + validation.suggestion + '</small>' : ''}
            </div>
        `;
    } else {
        result.innerHTML = `
            <div class="alert alert-warning alert-sm mb-0">
                <i class="fas fa-exclamation-triangle"></i> 
                <strong>格式提示：</strong>${validation.message}
                ${validation.suggestion ? '<br><small>建议：' + validation.suggestion + '</small>' : ''}
            </div>
        `;
    }
}

function validateEditUrl() {
    const input = document.getElementById('edit_url');
    const result = document.getElementById('editUrlValidationResult');
    const url = input.value.trim();
    
    if (!url) {
        result.innerHTML = '';
        return;
    }
    
    const validation = validateUrlFormat(url);
    
    if (validation.valid) {
        result.innerHTML = `
            <div class="alert alert-success alert-sm mb-0">
                <i class="fas fa-check-circle"></i> 
                <strong>验证通过：</strong>${validation.type}
                ${validation.suggestion ? '<br><small>' + validation.suggestion + '</small>' : ''}
            </div>
        `;
    } else {
        result.innerHTML = `
            <div class="alert alert-warning alert-sm mb-0">
                <i class="fas fa-exclamation-triangle"></i> 
                <strong>格式提示：</strong>${validation.message}
                ${validation.suggestion ? '<br><small>建议：' + validation.suggestion + '</small>' : ''}
            </div>
        `;
    }
}

// URL格式验证通用函数
function validateUrlFormat(url) {
    // 完整HTTP/HTTPS URL
    if (/^https?:\/\//i.test(url)) {
        try {
            new URL(url);
            return {
                valid: true,
                type: '外部链接',
                suggestion: '将在新窗口打开'
            };
        } catch {
            return {
                valid: false,
                message: '外部链接格式错误',
                suggestion: '请检查URL是否完整，如：https://example.com'
            };
        }
    }
    
    // Django内部路径
    if (/^\/[\w\/-]*\/?$/.test(url)) {
        let type = 'Django内部路径';
        let suggestion = '';
        
        // 检测常见应用路径
        if (url.startsWith('/rbac/')) {
            type += ' (RBAC系统)';
            suggestion = '访问 RBAC 权限管理系统';
        } else if (url.startsWith('/pm/')) {
            type += ' (PM系统)';
            suggestion = '访问 PM 项目管理系统';
        } else if (url.startsWith('/admin/')) {
            type += ' (Django管理)';
            suggestion = '访问 Django 管理后台';
        }
        
        return {
            valid: true,
            type: type,
            suggestion: suggestion
        };
    }
    
    // 相对路径
    if (/^\.\.\//.test(url) || /^\.\//.test(url)) {
        return {
            valid: true,
            type: '相对路径',
            suggestion: '相对于当前页面的路径'
        };
    }
    
    // JavaScript 函数调用
    if (/^javascript:/i.test(url)) {
        return {
            valid: false,
            message: '不允许使用 JavaScript 协议',
            suggestion: '请使用 HTTP/HTTPS 链接或 Django 路径'
        };
    }
    
    // 其他情况
    return {
        valid: false,
        message: 'URL 格式不支持',
        suggestion: '请使用以下格式：/app/path/、https://domain.com 或 ../path/'
    };
}

// 为 URL 输入框添加实时验证
document.addEventListener('DOMContentLoaded', function() {
    const urlInput = document.getElementById('urlInput');
    const editUrlInput = document.getElementById('edit_url');
    
    if (urlInput) {
        urlInput.addEventListener('input', function() {
            setTimeout(validateUrl, 300); // 防抖动
        });
        urlInput.addEventListener('blur', validateUrl);
    }
    
    if (editUrlInput) {
        editUrlInput.addEventListener('input', function() {
            setTimeout(validateEditUrl, 300);
        });
        editUrlInput.addEventListener('blur', validateEditUrl);
    }
});

// 全选功能
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.menu-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
    });
});

// 添加菜单
function submitAddMenu() {
    const form = document.getElementById('addMenuForm');
    const formData = new FormData(form);
    
    // 获取URL值（从新的输入框）
    const urlValue = document.getElementById('urlInput').value.trim();
    if (!urlValue) {
        alert('请输入菜单链接');
        return;
    }
    
    // 验证URL格式
    const validation = validateUrlFormat(urlValue);
    if (!validation.valid) {
        alert('链接格式错误：' + validation.message);
        return;
    }
    
    // 获取选中的角色ID
    const roleIds = [];
    form.querySelectorAll('input[name="role_ids"]:checked').forEach(input => {
        roleIds.push(parseInt(input.value));
    });
    
    // 安全处理 sort_order 字段
    let sortOrder = 0;
    const sortOrderValue = formData.get('sort_order');
    if (sortOrderValue && sortOrderValue.trim() !== '') {
        const parsed = parseInt(sortOrderValue);
        if (!isNaN(parsed)) {
            sortOrder = parsed;
        }
    }
    
    const data = {
        name: formData.get('name'),
        code: formData.get('code'),
        description: formData.get('description'),
        icon: formData.get('icon'),
        url: urlValue, // 使用验证后的URL
        color: formData.get('color'),
        sort_order: sortOrder, // 使用处理后的值
        role_ids: roleIds
    };
    
    fetch('/rbac/menu_add/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('菜单添加成功！');
            location.reload();
        } else {
            alert('添加失败：' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试');
    });
}

// 编辑菜单
function editMenu(menuId) {
    // 从表格中获取菜单数据
    const row = document.querySelector(`tr[data-menu-id="${menuId}"]`);
    const name = row.querySelector('.fw-bold').textContent;
    const code = row.querySelector('.text-muted').textContent;
    const url = row.querySelector('a[href]').getAttribute('href');
    
    // 填充编辑表单
    document.getElementById('edit_menu_id').value = menuId;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_code').value = code;
    document.getElementById('edit_url').value = url; // 填充URL到新的输入框
    
    // 验证URL
    validateEditUrl();
    
    // 获取菜单的角色信息
    fetch(`/rbac/get_menu_roles/${menuId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清除所有角色选择
                document.querySelectorAll('#editMenuModal input[name="role_ids"]').forEach(input => {
                    input.checked = false;
                });
                // 选中对应的角色
                data.role_ids.forEach(roleId => {
                    const checkbox = document.getElementById(`edit_role_${roleId}`);
                    if (checkbox) {
                        checkbox.checked = true;
                    }
                });
            }
        })
        .catch(error => {
            console.error('Error fetching menu roles:', error);
        });
    
    // 显示编辑模态框
    const modal = new bootstrap.Modal(document.getElementById('editMenuModal'));
    modal.show();
}

function submitEditMenu() {
    const form = document.getElementById('editMenuForm');
    const formData = new FormData(form);
    const menuId = formData.get('menu_id');
    
    // 获取URL值（从新的输入框）
    const urlValue = document.getElementById('edit_url').value.trim();
    if (!urlValue) {
        alert('请输入菜单链接');
        return;
    }
    
    // 验证URL格式
    const validation = validateUrlFormat(urlValue);
    if (!validation.valid) {
        alert('链接格式错误：' + validation.message);
        return;
    }
    
    // 获取选中的角色ID
    const roleIds = [];
    form.querySelectorAll('input[name="role_ids"]:checked').forEach(input => {
        roleIds.push(parseInt(input.value));
    });
    
    // 安全处理 sort_order 字段
    let sortOrder = 0;
    const sortOrderValue = formData.get('sort_order');
    if (sortOrderValue && sortOrderValue.trim() !== '') {
        const parsed = parseInt(sortOrderValue);
        if (!isNaN(parsed)) {
            sortOrder = parsed;
        }
    }
    
    const data = {
        name: formData.get('name'),
        code: formData.get('code'),
        description: formData.get('description'),
        icon: formData.get('icon'),
        url: urlValue, // 使用验证后的URL
        color: formData.get('color'),
        sort_order: sortOrder, // 使用处理后的值
        role_ids: roleIds
    };
    
    fetch(`/rbac/menu_edit/${menuId}/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('菜单更新成功！');
            location.reload();
        } else {
            alert('更新失败：' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试');
    });
}

// 删除菜单
function deleteMenu(menuId, menuName) {
    if (confirm(`确定要删除菜单"${menuName}"吗？此操作不可恢复。`)) {
        fetch(`/rbac/menu_delete/${menuId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('菜单删除成功！');
                location.reload();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
}

// 切换菜单状态
function toggleMenuStatus(menuId) {
    fetch(`/rbac/menu_toggle_status/${menuId}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            location.reload();
        } else {
            alert('操作失败：' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试');
    });
}
</script>
{% endblock %}